package logic

import (
	"context"
	"edu-pro/models/cache"
	"edu-pro/models/mysql"
	"encoding/json"
	"fmt"
	"time"

	"edu-pro/edurpc/edurpc"
	"edu-pro/edurpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type CourseListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCourseListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CourseListLogic {
	return &CourseListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CourseListLogic) CourseList(in *edurpc.CourseListRequest) (*edurpc.CourseListResponse, error) {
	//课程列表
	var lists []mysql.CourseData
	key := fmt.Sprintf("course_list_%s", in)
	result, _ := cache.RDB.Get(l.ctx, key).Result()
	if result == "" {
		tx := mysql.DB.Debug().Model(mysql.Course{}).
			Select("courses.*,users.nickname").
			Joins("left join users on users.id = courses.user_id").
			Scopes(mysql.Paginate(int(in.Page), int(in.Size)))
		if in.SortType != 0 && in.SortMethod == "" {
			in.SortMethod = "desc"
		}
		if in.SortType == 0 {
			tx.Order("learn_count desc")
		} else if in.SortType == 1 {
			tx.Order("created_at desc")
		}
		tx.Order("created_at desc")
		if in.TitleSearch != "" {
			tx.Where("title like ?", "%"+in.TitleSearch+"%")
		}
		if in.CateSearch != "" {
			tx.Where("category = ?", in.CateSearch)
		}
		tx.Find(&lists)
		marshal, _ := json.Marshal(lists)
		cache.RDB.Set(l.ctx, key, marshal, time.Minute*15)
	} else {
		json.Unmarshal([]byte(result), &lists)
	}

	var courseList []*edurpc.CourseList
	for _, data := range lists {
		list := edurpc.CourseList{
			Title:    data.Title,
			Nickname: data.Nickname,
			Category: data.Category,
			Price:    float32(data.Price),
			CoverUrl: data.CoverUrl,
		}
		courseList = append(courseList, &list)
	}
	var total int64
	mysql.DB.Debug().Model(&mysql.Course{}).Count(&total)
	return &edurpc.CourseListResponse{
		List:  courseList,
		Total: total,
	}, nil
}
